package com.bwie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.es.EsProd;
import com.bwie.mapper.ProdMapper;
import com.bwie.pojo.Prod;
import com.bwie.service.ProdService;
import com.bwie.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:杨珂
 * @CreateTime: 2025-03-29
 */



@RestController
@RequestMapping("/prod/es")
public class EsIndexController {

    @Autowired
    ProdMapper prodMapper;

    @Autowired
    ElasticsearchRestTemplate restTemplate;

    @PostMapping("/createIndex")
    public R createIndex() {
        //判断索引是否存在
        IndexOperations indexOps = restTemplate.indexOps(EsProd.class);
        boolean exists = indexOps.exists();
        if (exists) {
            indexOps.delete();
        }
        //创建索引
        indexOps.create();


        //手动创建映射
        Document mapping = indexOps.createMapping();
        indexOps.putMapping(mapping);

        return R.OK();
    }

    @PostMapping("/saveProdToEs/{prodId}")
    public R saveProdToEs(@PathVariable("prodId") Integer prodId) {

        Prod prod = prodMapper.selectById(prodId);

        if (prod == null) {
            return R.ERROR(500, "商品不存在");
        }

        EsProd esProd = BeanUtil.toBean(prod, EsProd.class);
        restTemplate.save(esProd);

        return R.OK();
    }

    @PostMapping("/getProdFromEs/{prodId}")
    public R getProdFromEs(@PathVariable("prodId") Integer prodId) {

        EsProd esProd = restTemplate.get("" + prodId, EsProd.class);
        if (esProd == null) {
            return R.ERROR(500, "商品不存在");
        }
        return R.OK(esProd);
    }

    @PostMapping("/delectProdFromEs/{prodId}")
    public R delectProdFromEs(@PathVariable("prodId") Integer prodId) {
        restTemplate.delete("" + prodId, EsProd.class);
        return R.OK();
    }

}
